package com.ruoyi.finance.protal.utils;

import com.github.pagehelper.util.StringUtil;
import com.ruoyi.finance.protal.constans.SystemConstant;
import com.ruoyi.finance.rules.entity.SzUser;
import com.ruoyi.finance.rules.mapper.SzUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Service
public class SzUserSessionImpl implements SzUserSession{

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SzUserMapper szUserMapper;

    @Override
    public Long getCurrentUserId(HttpServletRequest request) {
        String authHeader = request.getHeader(SystemConstant.getTOKEN()).replace("Bearer", "").trim();
        if(StringUtil.isNotEmpty(authHeader)){
            Long userId = (Long) redisTemplate.opsForValue().get(SystemConstant.getLoginUserPrefix() + authHeader);
            if (!StringUtils.isEmpty(userId)){
                redisTemplate.opsForValue().set(SystemConstant.getLoginUserPrefix() + authHeader,userId,604800, TimeUnit.SECONDS);
                return userId;
            }else{
                throw new IllegalStateException("请登录");
            }
        }else{
            throw new IllegalStateException("请登录");
        }
    }

    @Override
    public SzUser getCurrentUserInfo(HttpServletRequest request) {
        String authHeader = request.getHeader(SystemConstant.getTOKEN()).replace("Bearer", "").trim();
        if(StringUtil.isNotEmpty(authHeader)){
            Long userId = (Long) redisTemplate.opsForValue().get(SystemConstant.getLoginUserPrefix() + authHeader);
            if (!StringUtils.isEmpty(userId)){
                SzUser user = szUserMapper.selectById(userId);
                redisTemplate.opsForValue().set(SystemConstant.getLoginUserPrefix() + authHeader,userId,604800, TimeUnit.SECONDS);
                return user;
            }else{
                throw new IllegalStateException("请登录");
            }
        }else{
            throw new IllegalStateException("请登录");
        }
    }

}
